package controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import model.User;
import service.UserService;
import service.impl.UserServiceImpl;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");

        User userIndb = null;
        try {
            userIndb = userService.getUserByName(username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        if (userIndb == null) {
            request.setAttribute("msg", "当前用户名未注册");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        } else {
            if (userIndb.getPassword().equals(password)) {// 用户名密码正确
                //登录成功
                if ("yes".equals(rememberMe)) {
                    // 勾选了记住我
                    Cookie usernameCookie = new Cookie("username", username);
                    Cookie passwordCookie = new Cookie("password", password);
                    usernameCookie.setMaxAge(60 * 60 * 24 * 7);
                    passwordCookie.setMaxAge(60 * 60 * 24 * 7);
                    response.addCookie(usernameCookie);
                    response.addCookie(passwordCookie);
                }
                // 将用户名存入session中
                HttpSession session = request.getSession();
                session.setAttribute("username", username);
                // 重定向到/user
                response.sendRedirect(request.getContextPath() + "/user");
            } else {
                // 密码错误, 记录错误信息，转发到登录页面
                request.setAttribute("msg", "密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        }

    }
}